package br.edu.cesar.aula09;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class PrincipalActivity extends ActionBarActivity 
	implements TabListener {

	GoogleNewsListFragment f1;
	Fragment2 f2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_principal);


		f1 = (GoogleNewsListFragment)getSupportFragmentManager().findFragmentByTag("f1");
		f2 = (Fragment2)getSupportFragmentManager().findFragmentByTag("f2");
		
		if (f1 == null || f2 == null){
			f1 = new GoogleNewsListFragment();
			f2 = new Fragment2();
		
			getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.conteudoAbas, f1, "f1")
				.add(R.id.conteudoAbas, f2, "f2")
				.hide(f2)
				.commit();
		} 
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(
				ActionBar.NAVIGATION_MODE_TABS);
		
		Tab aba1 = actionBar.newTab();
		aba1.setText("Aba 1");
		aba1.setTabListener(this);
		
		Tab aba2 = actionBar.newTab();
		aba2.setText("Aba 2");
		aba2.setTabListener(this);
		
		actionBar.addTab(aba1);
		actionBar.addTab(aba2);
		
		if (savedInstanceState != null){
			actionBar.setSelectedNavigationItem(
					savedInstanceState.getInt("abaSelecionada"));
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("abaSelecionada", 
				getSupportActionBar().getSelectedNavigationIndex());
	}
	
	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		
		if (tab.getPosition() == 0){
			ft.show(f1).hide(f2);
		} else {
			ft.show(f2).hide(f1);
		}
		
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		
	}
	
	
	public static class Fragment1 extends Fragment {
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			TextView txt = new TextView(getActivity());
			txt.setText("Aba 1");
			return txt;
		}
		
	}

	public static class Fragment2 extends Fragment {
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			TextView txt = new TextView(getActivity());
			txt.setText("Aba 2");
			return txt;
		}
	}
}
